﻿using System;
using System.IO;

namespace Sort
{
    class QueueItem
    {
        public object message;
        public QueueItem next;
        public QueueItem(object message = null)
        {
            this.message = message;
            next = null;
        }
    }

    class LocklessQueue
    {
        private QueueItem first;
        private QueueItem last;

        public LocklessQueue()
        {
            first = new QueueItem();
            last = first;
        }

        public void PushMessage(object message)
        {
            last.next = new QueueItem(message);
            last = last.next;
        }

        public bool PopMessage(out object message)
        {
            if (first == last || first.next == null)
            {
                message = null;
                return false;
            }
            message = first.next.message;
            first = first.next;
            return true;
        }
    }

    class Log
    {
        private static LocklessQueue messageQueue;

        public Log()
        {
            messageQueue = new LocklessQueue();
        }

        public void Debug(string msg)
        {
            messageQueue.PushMessage("DEBUG " + DateTime.Now + " " + msg);
        }

        public void Info(string msg)
        {
            messageQueue.PushMessage("INFO " + DateTime.Now + " " + msg);
        }

        public void Fatal(string msg)
        {
            messageQueue.PushMessage("FATAL " + DateTime.Now + " " + msg);
        }

        public void WriteLogFile()
        {
            StreamWriter sw = new StreamWriter("log.txt", true);
            object msg;
            while (messageQueue.PopMessage(out msg))
            {
                sw.WriteLine(msg);
            }
            sw.Close();
        }
    }
}
